<template>
  <div id="app">
    <div v-if="ticketOut">
      <div style="margin: 10px;font-weight: bold;font-size: 18px;">获取中</div>
    </div>
    <div v-else>
      <div style="margin: 10px;font-weight: bold;font-size: 24px;">{{ year }} 年 {{ month }} 月 </div>
      <div style="margin: 10px;font-weight: bold;font-size: 18px;">
        项目日报总工时：{{ sum }}h 总人天：{{ (sum / 8).toFixed(1) }}天
      </div>
      <div style="margin: 10px;font-weight: bold;font-size: 18px;">
        非项目日报总工时：{{ sum_f * -1 }}h 总人天：{{ (sum_f * -1 / 8).toFixed(1) }}天
      </div>
      <HelloWorld style="height: 600px;" :chartData_x="chartData_x" :chartData_f="chartData_f" :xdata="xdata"
        :isDark="false" />
    </div>
  </div>
</template>

<script>
import HelloWorld from '@/components/HelloWorld.vue'
import axios from 'axios'

// import testData from '@/test.json'
export default {
  name: 'HomeView',
  components: {
    HelloWorld
  },
  data() {
    return {
      chartData_x: {},
      xdata: [],
      testData: [],
      chartData_f: [],
      sum_f: [],
      year: '',
      month: '',
      ticketOut: true
    }
  },
  created(query) {


  },
  async mounted(query) {
    const urlParams = new URLSearchParams(window.location.search);
    let ticket = urlParams.get('ticket');
    let year = urlParams.get('year');
    let month = urlParams.get('month');


    if (urlParams !== 3) {
      const currentRoute = this.$route;
      // 获取地址栏中的参数
      const ticketParam = currentRoute.query.ticket;
      if (!ticketParam) {
        this.$router.push({ path: '/about' });

      }
    }

    this.year = year
    this.month = month
    // 生成时间戳
    const { startTimeStamp, endTimeStamp } = this.generateMonthTimestamps(year, month);

    let result = await this.saveFormWightQuery(ticket)

    if (result) {


      await axios.post(`https://www.yunzhijia.com/workflow/api/v1/flowWeb/myFlowPageList?appId=10104&ticket=${ticket}`, {
        "flag": "all",
        "pageNumber": 1,
        "pageSize": 100,
        "lastId": null,
        "direction": "desc",
        "order": "_S_DATE",
        "appIds": [],
        "source": [],
        "formCodeIds": ["0d3b2a568bf848ebaf2f8704131e9fd0"],
        "startId": null,
        "startMilliseconds": null,
        "offset": 0,
        "searchItems": [],
        "_S_DATE": [startTimeStamp, endTimeStamp],
        "language": "zh-CN"
      })
        .then((response) => {
          if (response.data.errorCode == 0 || response.data.errorCode == 200) {
            this.ticketOut = false
            if (response.data.data.content.length > 0) {
              this.buildData(response.data.data.content, year, month)
            }

          } else {
            this.ticketOut = true
          }
        })
        .catch(function (error) {
          console.log(error);
        });


      await axios.post(`https://www.yunzhijia.com/workflow/api/v1/flowWeb/myFlowPageList?appId=10104&ticket=${ticket}`, {
        "flag": "all",
        "pageNumber": 1,
        "pageSize": 20,
        "lastId": null,
        "direction": "desc",
        "order": "_S_DATE",
        "appIds": [],
        "source": [],
        "formCodeIds": [
          "f01efc527a464c0891e1c338bc290361"
        ],
        "startId": null,
        "startMilliseconds": null,
        "offset": 0,
        "_S_DATE": [startTimeStamp, endTimeStamp],
        "language": "zh-CN"
      })
        .then((response) => {
          if (response.data.errorCode == 0 || response.data.errorCode == 200) {
            this.ticketOut = false
            if (response.data.data.content.length > 0) {
              this.buildData_fei(response.data.data.content, year, month)
            }
          } else {
            this.ticketOut = true
          }
        })
        .catch(function (error) {
          console.log(error);
        });

    }

  },
  methods: {
    // 非项目
    buildData_fei(testData, year, month) {
      let monthDates = this.generateMonthDates(year, month);
      let datas = {}

      let index1 = this.findIndex(testData[0].fieldContent, "status")
      let index2 = this.findIndex(testData[0].fieldContent, "Da_2")
      let index3 = this.findIndex(testData[0].fieldContent, "Nu_5")


      testData.forEach((item) => {

        let name = item.fieldContent[index1].value == 'FINISH' ? item.fieldContent[0].value.split('的')[1].split('日汇报')[0] : '未审核'
        if (item.fieldContent[index1].value !== 'TOSUBMIT') {
          if (!datas.hasOwnProperty(name)) {
            datas[name] = this.craeteData(monthDates)
          }

          item.fieldContent[index2].value.forEach((items, indexs) => {
            let dayIndex = this.findDayIndex(monthDates, items.slice(5, 10))
            if (dayIndex !== null) {
              datas[name][dayIndex].value += -1 * Number(item.fieldContent[index3].value[indexs])
              datas[name][dayIndex].valueValid += -1 * Number(item.fieldContent[index3].value[indexs])
            }
          })
        }

      })
      this.chartData_f = datas
      this.sum_f = this.isEmpty(datas) ? 0 : this.sumFun(datas)
    },
    buildData(testData, year, month) {
      // 生成横坐标
      let monthDates = this.generateMonthDates(year, month);
      let datas = {} // 确认人天数


      let index1 = this.findIndex(testData[0].fieldContent, "status")
      let index2 = this.findIndex(testData[0].fieldContent, "Da_0")
      let index3 = this.findIndex(testData[0].fieldContent, "Nu_0")
      let index4 = this.findIndex(testData[0].fieldContent, "Nu_7")


      testData.forEach((item) => {
        // 判断是否审核
        let name = item.fieldContent[index1].value == 'FINISH' ? item.fieldContent[0].value.split('的')[1].split('日汇报')[0] : '未审核'
        if (item.fieldContent[index1].value !== 'TOSUBMIT') {
          if (!datas.hasOwnProperty(name)) {
            // 如果没有name那么就创建一个
            datas[name] = this.craeteData(monthDates)
          }
          // 循环日期分录
          item.fieldContent[index2].value.forEach((items, indexs) => {
            // 裁切日期 MM-DD
            let dayIndex = this.findDayIndex(monthDates, items.slice(5, 10))
            if (dayIndex !== null) {
              // 如果是未审核则取未确认的工时
              datas[name][dayIndex].valueValid += (name == '未审核' ? Number(item.fieldContent[index4].value[indexs]) : Number(item.fieldContent[index4].value[indexs]))
              datas[name][dayIndex].value += (name == '未审核' ? Number(item.fieldContent[index3].value[indexs]) : Number(item.fieldContent[index3].value[indexs]))

              if (datas[name][dayIndex].valueValid !== datas[name][dayIndex].value) {
                datas[name][dayIndex].itemStyle = {
                  decal:{
                    symbol:'diamond'
                  }
                }
              }
            }
          })
        }

      })

      this.chartData_x = datas
      this.xdata = monthDates

      this.sum = this.isEmpty(datas) ? 0 : this.sumFun(datas)
    },

    // 找index
    findIndex(arr, key) {
      let indexs = null
      arr.forEach((item, index) => {
        if (item.codeId == key) {
          indexs = index
        }
      })
      return indexs

      // return arr.findIndex(item => item.codeId === key); // 假设我们要与 item.codeId 进行比较
    },
    // 创建空数组
    craeteData(monthDates) {
      let data = []
      monthDates.forEach((item, index) => {
        data.push({ value: 0, valueValid: 0 })
      })
      return data
    },
    generateMonthDates(year, month) {
      const startDate = new Date(year, month - 1, 1); // month is 0-indexed, so subtract 1
      const endDate = new Date(year, month, 0); // 0th day of next month is the last day of current month

      const datesArray = [];

      for (let date = startDate; date <= endDate; date.setDate(date.getDate() + 1)) {
        const formattedDate = `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
        datesArray.push(formattedDate);
      }

      return datesArray;
    },
    findDayIndex(arr, key) {
      let indexs = null
      arr.forEach((item, index) => {
        if (item == key) {
          indexs = index
        }
      })
      return indexs
    },
    sumFun(data) {
      let sum = 0
      for (let key in data) {
        sum += data[key].reduce((accumulator, currentValue) => accumulator + currentValue.valueValid, 0);
      }
      return sum
    },
    generateMonthTimestamps(year, month) {
      // 获取本月开始时间
      const startOfMonth = new Date(year, month - 1, 1);
      startOfMonth.setHours(0, 0, 0, 0);

      // 获取本月结束时间
      const endOfMonth = new Date(year, month, 0);
      endOfMonth.setHours(23, 59, 59, 999);

      // 将开始时间往前取2天
      const startTimeStamp = startOfMonth.getTime() - (2 * 24 * 60 * 60 * 1000);

      // 将结束时间往后取2天
      const endTimeStamp = endOfMonth.getTime() + (2 * 24 * 60 * 60 * 1000);

      return { startTimeStamp, endTimeStamp };
    },
    async saveFormWightQuery(ticket) {
      let return1 = false
      let return2 = false
      let data1 = { "codeId": "0d3b2a568bf848ebaf2f8704131e9fd0", "type": "start", "widgetVos": [{ "codeId": "_S_TITLE", "selected": true }, { "codeId": "_S_SERIAL", "selected": true }, { "codeId": "_S_DATE", "selected": true }, { "codeId": "activityName", "selected": true }, { "codeId": "approvers", "selected": true }, { "codeId": "status", "selected": true }, { "codeId": "Nu_7", "selected": true }, { "codeId": "Nu_0", "selected": true }, { "codeId": "Da_0", "selected": true }, { "codeId": "Da_1", "selected": true }, { "codeId": "_S_URGENCY_DEGREE", "selected": false }, { "codeId": "printed", "selected": false }, { "codeId": "Ac_0", "selected": false }, { "codeId": "Ac_0|DETAIL_SUMVALUE", "selected": false }, { "codeId": "Ac_1", "selected": false }, { "codeId": "Ac_1|DETAIL_SUMVALUE", "selected": false }, { "codeId": "Bd_1", "selected": false }, { "codeId": "Bd_10", "selected": false }, { "codeId": "Bd_11", "selected": false }, { "codeId": "Bd_3", "selected": false }, { "codeId": "Bd_5", "selected": false }, { "codeId": "Bd_6", "selected": false }, { "codeId": "Bd_8", "selected": false }, { "codeId": "Da_2", "selected": false }, { "codeId": "Da_3", "selected": false }, { "codeId": "Ff_2", "selected": false }, { "codeId": "Nu_0|DETAIL_SUMVALUE", "selected": false }, { "codeId": "Nu_11", "selected": false }, { "codeId": "Nu_11|DETAIL_SUMVALUE", "selected": false }, { "codeId": "Nu_12", "selected": false }, { "codeId": "Nu_13", "selected": false }, { "codeId": "Nu_14", "selected": false }, { "codeId": "Nu_14|DETAIL_SUMVALUE", "selected": false }, { "codeId": "Nu_15", "selected": false }, { "codeId": "Nu_15|DETAIL_SUMVALUE", "selected": false }, { "codeId": "Nu_7|DETAIL_SUMVALUE", "selected": false }, { "codeId": "Nu_8", "selected": false }, { "codeId": "Nu_8|DETAIL_SUMVALUE", "selected": false }, { "codeId": "Nu_9", "selected": false }, { "codeId": "Ra_0", "selected": false }, { "codeId": "Ra_1", "selected": false }, { "codeId": "Ta_0", "selected": false }, { "codeId": "Te_18", "selected": false }, { "codeId": "Te_20", "selected": false }, { "codeId": "Te_5", "selected": false }, { "codeId": "Te_6", "selected": false }, { "codeId": "_S_APPLY", "selected": false }, { "codeId": "_S_DEPT", "selected": false }, { "codeId": "Dd_0", "selected": false }, { "codeId": "Dd_1", "selected": false }, { "codeId": "Dd_3", "selected": false }, { "codeId": "Dd_4", "selected": false }], "widgetLinkRecordsMap": {}, "language": "zh-CN" }
      let data2 = { "codeId": "f01efc527a464c0891e1c338bc290361", "type": "start", "widgetVos": [{ "codeId": "_S_TITLE", "selected": true }, { "codeId": "_S_SERIAL", "selected": true }, { "codeId": "_S_DATE", "selected": true }, { "codeId": "activityName", "selected": true }, { "codeId": "approvers", "selected": true }, { "codeId": "_S_URGENCY_DEGREE", "selected": true }, { "codeId": "status", "selected": true }, { "codeId": "Nu_5", "selected": true }, { "codeId": "Nu_5|DETAIL_SUMVALUE", "selected": true }, { "codeId": "Da_2", "selected": true }, { "codeId": "Da_3", "selected": true }, { "codeId": "printed", "selected": false }, { "codeId": "Da_0", "selected": false }, { "codeId": "Da_1", "selected": false }, { "codeId": "Ds_0", "selected": false }, { "codeId": "Ds_1", "selected": false }, { "codeId": "Ps_0", "selected": false }, { "codeId": "Ra_3", "selected": false }, { "codeId": "Ra_4", "selected": false }, { "codeId": "Rd_0", "selected": false }, { "codeId": "Te_15", "selected": false }, { "codeId": "Te_16", "selected": false }, { "codeId": "Te_17", "selected": false }, { "codeId": "Te_18", "selected": false }, { "codeId": "Te_19", "selected": false }, { "codeId": "_S_APPLY", "selected": false }, { "codeId": "_S_DEPT", "selected": false }, { "codeId": "iw_0", "selected": false }, { "codeId": "iw_1", "selected": false }, { "codeId": "iw_4", "selected": false }, { "codeId": "iw_5", "selected": false }, { "codeId": "Dd_0", "selected": false }], "widgetLinkRecordsMap": {}, "language": "zh-CN" }
      await axios.post(`https://www.yunzhijia.com/workflow/api/v1/formTemplate/saveFormWightQuery?appId=10104&ticket=${ticket}`, data1)
        .then((response) => {
          if (response.data.errorCode == 0 || response.data.errorCode == 200) {
            return1 = true
          }
        })
        .catch(function (error) {
          console.log(error);
        });

      await axios.post(`https://www.yunzhijia.com/workflow/api/v1/formTemplate/saveFormWightQuery?appId=10104&ticket=${ticket}`, data2)
        .then((response) => {
          if (response.data.errorCode == 0 || response.data.errorCode == 200) {
            return2 = true
          }
        })
        .catch(function (error) {
          console.log(error);
        });


      return return1 && return2

    },
    isEmpty(obj) {
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          return false;
        }
      }
      return true;
    },
    deepCopy(obj) {
      if (obj === null || typeof obj !== 'object') {
        return obj;
      }

      let copy = Array.isArray(obj) ? [] : {};

      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          copy[key] = this.deepCopy(obj[key]);
        }
      }

      return copy;
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
